package cn.kgc.javaweb.servlet;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import cn.kgc.javaweb.entity.User;
import cn.kgc.javaweb.service.UserService;
import cn.kgc.javaweb.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author: mosin
 * @version: v1.0  2022/3/24
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    //登录
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("登录方法被调用");
        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");
        String rememberMe = req.getParameter("rememberMe");

        //将用户登录的数据 用户名 密码 封装成User对象 进行数据查询
        User user = User.builder().username(username).password(SecureUtil.md5(password)).build();
        //获取当前会话中的验证码
        String code = (String) req.getSession().getAttribute("captcha");

        //判定用户是否登录成功
        HashMap<String, Object> res = new HashMap<>();
        if (captcha.equals(code)) {
            boolean b = userService.login(user);
            System.out.println("b"+b);
            if (b) {//登录成功   判定是否要记住我
                Cookie ck1;
                Cookie ck2;
                Cookie ck3;
                if ("true".equals(rememberMe)) { // 记住我  将数据放入cookie 响应给前端进行缓存
                    ck1 = new Cookie("username", username);
                    ck2 = new Cookie("password", password);
                    ck3 = new Cookie("rememberMe", rememberMe);

                } else {//销毁前端的cookie缓存
                    ck1 = new Cookie("username", "");
                    ck2 = new Cookie("password", "");
                    ck3 = new Cookie("rememberMe", "");
                    ck1.setMaxAge(0);
                    ck2.setMaxAge(0);
                    ck3.setMaxAge(0);
                }

                resp.addCookie(ck1);
                resp.addCookie(ck2);
                resp.addCookie(ck3);

                res.put("code", 200);
                res.put("msg", "登录成功");
            } else {
                res.put("code", 500);
                res.put("msg", "用户名或者密码错误");
            }

        } else { //验证码错误
            res.put("code", 500);
            res.put("msg", "验证码错误");
        }
        // 以json格式将后台处理的结果返回   java对象  res  ->json
        String s = JSONUtil.toJsonStr(res);
        //设置响应格式  json
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(s);
        writer.close();

    }

    //注册
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("注册方法被调用");

        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //将前台获取的数据  封装成对象  密码加密
        password = SecureUtil.md5(password);
        User user = User.builder().password(password).username(username).build();

        // TODO  将数据向后台传递完成注册    1.查询当前用户是否存在（在前端通过异步请求完成）   true  返回用户名不可用

        boolean b = userService.addUser(user); //  true  注册成功  false  失败
        //判定用户是否注册成功
        HashMap<String, Object> res = new HashMap<>();
        if (b) {
            res.put("code", 200);
            res.put("msg", "注册成功");
        } else {
            res.put("code", 500);
            res.put("msg", "注册失败");
        }
        // 以json格式将后台处理的结果返回   java对象  res  ->json
        String s = JSONUtil.toJsonStr(res);

        //设置响应格式  json
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(s);
        writer.close();
    }


    //获取验证码
    protected void getCaptcha(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("验证码方法被调用");
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(350, 100, 4, 4);
        //获取生成的验证码
        String code = captcha.getCode();
        System.out.println("code = " + code);

        //将验证码存入session 以便登录验证
        req.getSession().setAttribute("captcha", code);

        //图形验证码写出，可以写出到文件，也可以写出到流
        ServletOutputStream outputStream = resp.getOutputStream();
        captcha.write(outputStream);
        outputStream.close();
    }

}
